package com.pesking.core.sqlparser.processor;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;
import com.pesking.core.sysparam.SystemParameterManage;
import com.pesking.core.util.DateUtils;
import com.pesking.core.util.StringUtils;

public class DateAddSqlParameterHandler extends SqlParameterProcessor {

	
	@Override
	public void handle(StringBuilder sbSQL, Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		sbSQL.append("?");
		processors.add(sqlParameter);
	}


	@Override
	public void setParameter(PreparedStatement ps, Parameter parameter, int index,SqlParameter sqlParameter) throws SQLException {
		String dateName = sqlParameter.getName();
		String intervalValue = sqlParameter.getField(2);
		String dateType = sqlParameter.getField(1);
		int diffType = DateUtils.DIFF_DAY;
		if (!StringUtils.isBlank(dateType)){
			if ("Y".equalsIgnoreCase(dateType)){
				diffType = DateUtils.DIFF_YEAR;
			}
			else if ("M".equalsIgnoreCase(dateType)){
				diffType = DateUtils.DIFF_MONTH;
			}
			else if ("D".equalsIgnoreCase(dateType)){
				diffType = DateUtils.DIFF_DAY;
			}
			else if ("H".equalsIgnoreCase(dateType)){
				diffType = DateUtils.DIFF_HOUR;
			}
			else if ("MI".equalsIgnoreCase(dateType)){
				diffType = DateUtils.DIFF_MINUTE;
			}
			else if ("S".equalsIgnoreCase(dateType)){
				diffType = DateUtils.DIFF_SECOND;
			}
		}
		Timestamp ts = null;
		if (!StringUtils.isBlank(dateName)){
			ts = parameter.getTimestampParameter(dateName);
		}
		if (ts == null){
			ts = DateUtils.getCurrentTimestamp();
		}
		int n = 1;
		if (!StringUtils.isBlank(intervalValue)){
			String str = SystemParameterManage.getString(intervalValue);
			if (!StringUtils.isBlank(str)){
				n = Integer.parseInt(intervalValue);
			}
		}
		
		ts = DateUtils.dateDiff(ts, n, diffType);
		ps.setTimestamp(index, ts);
	}


	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"DATE_ADD"});
	}
}
